﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.Data.SqlClient;
using System.Runtime.InteropServices;

namespace dreametryVersion2
{
    public partial class frmChat : Form
    {
        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;
        [DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();


        Socket sck;
        EndPoint epLocal, epRemote;
        String sLocal, sRemote;
        String plocal = "100", pRemote = "200";
        
        private void btnRefreshavailable_Click(object sender, EventArgs e)
        {
            string commandText = "SELECT * FROM employee Where pc_ip_address IS NOT NULL";

            using (SqlConnection connection = new SqlConnection(global.conString))
            using (SqlDataAdapter adapter = new SqlDataAdapter(commandText, connection))
            {
                DataTable users = new DataTable();
                 adapter.Fill(users);
                
                 cmbOnline.DisplayMember = "fullname";
                 cmbOnline.ValueMember = "emp_id";
                 cmbOnline.DataSource = users;      
            }
        }
        public frmChat()
        {
            InitializeComponent();

            sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        }

        private void cmbOnline_SelectedIndexChanged(object sender, EventArgs e)
        {
            getIP();
        }

        private void FrmAdmin_Load(object sender, EventArgs e)
        {
            btnConnect.BackColor = ColorTranslator.FromHtml(global.themeColor);
            btnDisconnect.BackColor = ColorTranslator.FromHtml(global.themeColor);
            btnRefreshavailable.BackColor = ColorTranslator.FromHtml(global.themeColor);
            btnSendChat.BackColor = ColorTranslator.FromHtml(global.themeColor);

            btnRefreshavailable.PerformClick();
            string commandText = "SELECT pc_ip_address FROM employee WHERE emp_id = @Name";

            using (SqlConnection connection = new SqlConnection(global.conString))
            {
                SqlCommand command = new SqlCommand(commandText, connection);
                command.Parameters.Add("@Name", SqlDbType.Int, 5).Value = global.employeeID;
                try
                {
                    command.Connection.Open();
                    sLocal = command.ExecuteScalar().ToString();
                }
                catch
                {
                    sLocal = "";

                }
                finally
                {
                    command.Connection.Close();
                }
            }
        }

        private void btnSendChat_Click(object sender, EventArgs e)
        {
            //clicked = false;
            try
            {
                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                byte[] msg = new byte[1500];

             
                    msg = enc.GetBytes(txtMessage.Text);
             
                sck.Send(msg);
               
                    txtMessage.Clear();
            
                
            }
            catch (Exception exp)
            {
                Console.Write(exp);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
            frmChat fra = new frmChat();
            fra.Show();
        }

        private void btnReturnHome_Click(object sender, EventArgs e)
        {
            frmMain frm = new frmMain();
            frm.Show();
            this.Close();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmChat_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            }
        }

        public void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                epLocal = new IPEndPoint(IPAddress.Parse(sLocal), Convert.ToInt32(plocal));
                sck.Bind(epLocal);

                epRemote = new IPEndPoint(IPAddress.Parse(sRemote), Convert.ToInt32(pRemote));
                sck.Connect(epRemote);
                

                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallback), buffer);

                btnConnect.Text = "Connected";
                txtMessage.Enabled = true;
                btnSendChat.Enabled = true;
                btnConnect.Enabled = false;


            }
            catch (Exception exp)
            {
                Console.Write(exp);
            }
        }

        private void MessageCallback(IAsyncResult aResult)
        {
            try
            {
                int size = sck.EndReceiveFrom(aResult, ref epRemote);
                if (size > 0)
                {
                    byte[] receivedData = new byte[1464];

                    receivedData = (byte[])aResult.AsyncState;

                    ASCIIEncoding eEncoding = new ASCIIEncoding();
                    string receivedMessage = eEncoding.GetString(receivedData);

                    //  int x = listBox1.Items.Count - 1;
                    //  listBox1.Items.RemoveAt(x);


                    message.adminMessage(receivedMessage, chat.GetLocalIP(), "200");


                }
                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallback), buffer);



            }
            catch (Exception exp)
            {
                Console.Write(exp);
            }
        }
        private void getIP()
        {
            string commandText = "SELECT pc_ip_address FROM employee WHERE emp_id = @Name ";

            using (SqlConnection connection = new SqlConnection(global.conString))
            {
                SqlCommand command = new SqlCommand(commandText, connection);
                command.Parameters.Add("@Name", SqlDbType.Int, 5).Value = cmbOnline.SelectedValue.ToString();
                try
                {
                    command.Connection.Open();
                    sRemote = command.ExecuteScalar().ToString();
                }
                catch
                {
                    sRemote = "";

                }
                finally
                {
                    command.Connection.Close();
                }



            }
        }


    }
}
